package com.yyyit.bg2.tools;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
//import net.sf.json.JSONObject;

/*
 * 千丁接口测试工具类
 * 提供单个接口、多个接口，接口加模块等类型的测试
 * 1.0版本计划调用下链接中的社区接口
 * http://wiki.qdingnet.com/pages/viewpage.action?pageId=4622045
 */
public class ApiTest {

	public static int apiTest(String URL) {

		try {
			// 创建连接
			URL url = new URL(URL);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");

			connection.connect();

			// POST请求
			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());
			out.writeBytes("email=hejianmin@netposa.com&password=doudou456&_t=");
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}

			reader.close();
			// 断开连接
			connection.disconnect();
			System.out.println("OK" + sb);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return 1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return 1;
		} catch (IOException e) {
			e.printStackTrace();
			return 1;
		}
		return 0;

	}

	// 链接组
	public static int apisTest(String URL[]) {
		for (int i = 0; i < URL.length; i++) {
			apiTest(URL[i]);
		}
		return 0;
	}

	// 模块加链接
	public static int apiTest(String model, String URL) {
		System.out.println(model);
		apiTest(URL);
		return 0;
	}

	// 模块加链接组
	public static int apisTest(String model, String URL[]) {
		System.out.println(model);
		for (int i = 0; i < URL.length; i++) {
			apiTest(URL[i]);
		}
		return 0;
	}

	public static void main(String args[]) {
		String DEMOURL = "http://qaboss.qdingnet.com//brick/app/data/project.json?cityId=3&timestamp=1425030631968&qdPlatform=android&qdDevice=cancro&qdVersion=1.1.1";
		apiTest(DEMOURL, "社区");
	}

}